package com.zxy.ziems.server.statistics.controller;

import com.zxy.ziems.server.dto.DataQueryDto;
import com.zxy.ziems.server.energy.pojo.vo.EleTotalSystemVo;
import com.zxy.ziems.server.statistics.service.EleService;
import com.zxy.ziems.server.utils.StringUtils;
import com.zxy.ziems.server.vo.ChartVo;
import com.zxy.ziems.server.vo.ChartYAxisVo;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 电科
 *
 * @Copyright (C),
 * @ClassName: EleController
 * @Author: yanzhiwei
 * @Description:
 * @Date: 2024/7/16 16:22
 */
@RestController
@Validated
@RequestMapping("/api/chart/dict")
public class EleController {

    @Autowired
    private EleService eleService;

    /**
     * 电科_各科室分项
     *
     * @param dataQueryDto
     * @return
     */
    @GetMapping("/eleTypeOneReport")
    public ChartVo eleTypeOneReport(DataQueryDto dataQueryDto) {
        return eleService.eleTypeOneReport(dataQueryDto);
    }

    /**
     * 电科_各科室分项_楼栋
     *
     * @param dataQueryDto
     * @return
     */
    @GetMapping("/eleTypeOneReportBuilding")
    public ChartVo eleTypeOneReportBuilding(DataQueryDto dataQueryDto) {
        return eleService.eleTypeOneReportBuilding(dataQueryDto);
    }

    /**
     * 电科_各科室汇总
     *
     * @param dataQueryDto
     * @return
     */
    @GetMapping("/eleTypeAllReport")
    public ChartVo eleTypeAllReport(DataQueryDto dataQueryDto) {
        return eleService.eleTypeAllReport(dataQueryDto);
    }

    /**
     * 电科_各科室汇总(系统)
     *
     * @param dataQueryDto
     * @return
     */
    @GetMapping("/eleTypeAllReportSys")
    public ChartVo eleTypeAllReportSys(DataQueryDto dataQueryDto) {
        return eleService.eleTypeAllReportSys(dataQueryDto);
    }

    /**
     * 电科_各科室汇总楼栋
     *
     * @param dataQueryDto
     * @return
     */
    @GetMapping("/eleTypeAllReportBuilding")
    public ChartVo eleTypeAllReportBuilding(DataQueryDto dataQueryDto) {
        return eleService.eleTypeAllReportBuilding(dataQueryDto);
    }

    /**
     * 电科_各科室汇总系统
     *
     * @param dataQueryDto
     * @return
     */
    @GetMapping("/eleTypeAllReportSystem")
    public EleTotalSystemVo eleTypeAllReportSystem(DataQueryDto dataQueryDto) {
        return eleService.eleTypeAllReportSystem(dataQueryDto);
    }
    /**
     * 电科_各科室汇总系统(sheet2)
     *
     * @param dataQueryDto
     * @return
     */
    @GetMapping("/eleTypeAllReportSysRatio")
    public EleTotalSystemVo eleTypeAllReportSysRatio(DataQueryDto dataQueryDto) {
        return eleService.eleTypeAllReportSysRatio(dataQueryDto);
    }

    /**
     * 各科室汇总导出
     * @param request
     * @param response
     * @param dataQueryDto
     * @return
     */
    @GetMapping("/export")
    public void export(HttpServletRequest request, HttpServletResponse response, DataQueryDto dataQueryDto) {
        // 设置 HTTP 响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        String fileName = "各科室汇总.xlsx";
        String encodedFileName = null;
        try {
            encodedFileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }

        response.setHeader("Content-Disposition", "attachment; filename=\"" + encodedFileName + "\"");


        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();

        try (InputStream fis = classLoader.getResourceAsStream("template/electrical-template.xlsx")) {

            Workbook workbook = new XSSFWorkbook(fis);

            // 设置sheet1
            sheet1(workbook, dataQueryDto);

            // 设置sheet2
            setSheet2(workbook, dataQueryDto);

            // 写入数据
            workbook.write(response.getOutputStream());

            workbook.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void sheet1(Workbook workbook, DataQueryDto dataQueryDto) {

        ChartVo chartVo = eleService.eleTypeAllReport(dataQueryDto);

        CellStyle style = getCellStyle(workbook);

        List<String> xAxisList = chartVo.getXAxisList();
        List<ChartYAxisVo> yAxisList = chartVo.getYAxisList();
        Sheet sheet = workbook.getSheetAt(0); // 假设我们要修改第一个工作表

        // 修改特定单元格的值
        Row row = sheet.getRow(0); // 假设我们要修改第一行
        for (int i = 0; i < xAxisList.size(); i++) {
            Cell cell = row.createCell(i + 3);
            String s1 = xAxisList.get(i);
            cell.setCellValue(StringUtils.isEmpty(s1) ? "" : s1);
            cell.setCellStyle(style);
        }
        Map<String, ChartYAxisVo> collect = yAxisList.stream().collect(Collectors.toMap(ChartYAxisVo::getName, v -> v));

        int lastRowNum = sheet.getLastRowNum();
        for (int i = 1; i <= lastRowNum; i++) {
            Row row1 = sheet.getRow(i);
            Cell cell1 = row1.getCell(2);
            if (cell1.getStringCellValue().equals("")) {
                cell1 = row1.getCell(1);
            }
            ChartYAxisVo chartYAxisVo = collect.get(cell1.getStringCellValue());
            if (chartYAxisVo == null) continue;
            List<BigDecimal> data = chartYAxisVo.getData();
            for (int i1 = 0; i1 < data.size(); i1++) {
                Cell cell = row1.createCell(i1 + 3);
                cell.setCellStyle(style);
                if (data.get(i1) != null) {
                    cell.setCellValue(data.get(i1).toString());
                }
            }
        }

        EleTotalSystemVo ratio = eleService.eleTypeAllReportSystem(dataQueryDto);
        int rowNum = lastRowNum + 2;
        Row row1 = sheet.createRow(rowNum++);
        List<String> xAxisList1 = ratio.getTitleList();
        Cell cell = row1.createCell(0);
        cell.setCellStyle(style);
        cell.setCellValue("类别");
        for (int i = 0; i < xAxisList1.size(); i++) {
            Cell cell1 = row1.createCell(i + 1);
            cell1.setCellStyle(style);
            cell1.setCellValue(xAxisList1.get(i));
        }
        Row row2 = sheet.createRow(rowNum++);
        Cell cell1 = row2.createCell(0);
        cell1.setCellStyle(style);
        cell1.setCellValue("数值");
        List<BigDecimal> yAxisList1 = ratio.getValueList();
        for (int i = 0; i < yAxisList1.size(); i++) {
            Cell cell2 = row2.createCell(i + 1);
            cell2.setCellStyle(style);
            cell2.setCellValue(yAxisList1.get(i).toString());
        }
        Row row3 = sheet.createRow(rowNum++);
        Cell cell3 = row3.createCell(0);
        cell3.setCellStyle(style);
        cell3.setCellValue("占比");
        List<BigDecimal> ratioList = ratio.getRatioList();
        for (int i = 0; i < ratioList.size(); i++) {
            Cell cell2 = row3.createCell(i + 1);
            cell2.setCellStyle(style);
            cell2.setCellValue(ratioList.get(i).multiply(new BigDecimal(100)).setScale(2, RoundingMode.HALF_UP) + "%");
        }

    }

    @NotNull
    private static CellStyle getCellStyle(Workbook workbook) {
        CellStyle style = workbook.createCellStyle();

        // 设置外边框
        style.setBorderTop(BorderStyle.THIN);
        style.setBorderBottom(BorderStyle.THIN);
        style.setBorderLeft(BorderStyle.THIN);
        style.setBorderRight(BorderStyle.THIN);
        return style;
    }

    private void setSheet2(Workbook workbook, DataQueryDto dataQueryDto) {
        ChartVo chartVo = eleService.eleTypeAllReportSys(dataQueryDto);

        CellStyle style = getCellStyle(workbook);

        List<String> xAxisList = chartVo.getXAxisList();
        List<ChartYAxisVo> yAxisList = chartVo.getYAxisList();
        Sheet sheet = workbook.getSheetAt(1); // 假设我们要修改第一个工作表

        // 修改特定单元格的值
        Row row = sheet.getRow(0); // 假设我们要修改第一行
        for (int i = 0; i < xAxisList.size(); i++) {
            Cell cell = row.createCell(i + 3);
            cell.setCellStyle(style);
            String s1 = xAxisList.get(i);
            cell.setCellValue(StringUtils.isEmpty(s1) ? "" : s1);
        }
        Map<String, ChartYAxisVo> collect = yAxisList.stream().collect(Collectors.toMap(ChartYAxisVo::getName, v -> v));

        int lastRowNum = sheet.getLastRowNum();
        for (int i = 1; i <= lastRowNum; i++) {
            Row row1 = sheet.getRow(i++);
            Cell cell1 = row1.getCell(1);
            if (cell1.getStringCellValue().equals("")) {
                cell1 = row1.getCell(0);
            }
            ChartYAxisVo chartYAxisVo = collect.get(cell1.getStringCellValue());
            if (chartYAxisVo == null) continue;
            List<BigDecimal> data = chartYAxisVo.getData();
            List<BigDecimal> ratio = chartYAxisVo.getRatio();
            for (int i1 = 0; i1 < data.size(); i1++) {
                Cell cell = row1.createCell(i1 + 3);
                cell.setCellStyle(style);
                if (data.get(i1) != null) {
                    cell.setCellValue(data.get(i1).toString());
                }
            }
            Row row2 = sheet.getRow(i);
            for (int i1 = 0; i1 < ratio.size(); i1++) {
                Cell cell = row2.createCell(i1 + 3);
                cell.setCellStyle(style);
                if (ratio.get(i1) != null) {
                    cell.setCellValue(ratio.get(i1).multiply(new BigDecimal(100)).setScale(2, RoundingMode.HALF_UP) + "%");
                }
            }
        }

        EleTotalSystemVo ratio = eleService.eleTypeAllReportSysRatio(dataQueryDto);
        int rowNum = lastRowNum + 2;
        Row row1 = sheet.createRow(rowNum++);
        List<String> xAxisList1 = ratio.getTitleList();
        Cell cell = row1.createCell(0);
        cell.setCellStyle(style);
        cell.setCellValue("类别");
        for (int i = 0; i < xAxisList1.size(); i++) {
            Cell cell1 = row1.createCell(i + 1);
            cell1.setCellStyle(style);
            cell1.setCellValue(xAxisList1.get(i));
        }
        Row row2 = sheet.createRow(rowNum++);
        Cell cell1 = row2.createCell(0);
        cell1.setCellStyle(style);
        cell1.setCellValue("数值");
        List<BigDecimal> yAxisList1 = ratio.getValueList();
        for (int i = 0; i < yAxisList1.size(); i++) {
            Cell cell2 = row2.createCell(i + 1);
            cell2.setCellStyle(style);
            cell2.setCellValue(yAxisList1.get(i).toString());
        }
        Row row3 = sheet.createRow(rowNum++);
        Cell cell3 = row3.createCell(0);
        cell3.setCellStyle(style);
        cell3.setCellValue("占比");
        List<BigDecimal> ratioList = ratio.getRatioList();
        for (int i = 0; i < ratioList.size(); i++) {
            Cell cell2 = row3.createCell(i + 1);
            cell2.setCellStyle(style);
            cell2.setCellValue(ratioList.get(i).multiply(new BigDecimal(100)).setScale(2, RoundingMode.HALF_UP) + "%");
        }


    }

}
